﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace iPlaylistSync
{
    public class PlaylistReader
    {
        XmlDocument iTunesMusicLibrary;
        XmlNode playlist;
        XmlNode tracks;

        public PlaylistReader(string path)
        {
            //iTunesMusicLibrary = XDocument.Load(path);
            //playlist = XElement.Parse(iTunesMusicLibrary.Descendants("key").Single(inner => inner.Value == "Playlists").NextNode.ToString());
            //tracks = XElement.Parse(iTunesMusicLibrary.Descendants("key").Single(inner => inner.Value == "Tracks").NextNode.ToString());
            iTunesMusicLibrary = new XmlDocument();
            iTunesMusicLibrary.Load(path);
            playlist = iTunesMusicLibrary.SelectSingleNode("/plist/dict/key[text()='Playlists']/following-sibling::array");
            tracks = iTunesMusicLibrary.SelectSingleNode("/plist/dict/key[text()='Tracks']/following-sibling::dict");
            
        }

        public Track[] GetTracks(string listName)
        {
            XmlNodeList list = playlist.SelectNodes(
                "dict/key[text()='Name']/following-sibling::string[text()='"+listName+"']"+
                "/../key[text()='Playlist Items']/following-sibling::array/dict"
                );

            int tracksCnt = list.Count;
            Track[] result = new Track[tracksCnt];
            int i = 0;
            int locationOffset = 17;   // "file://localhost/".Length=17
            foreach (XmlNode item in list)
            {

                string id = item.SelectSingleNode("integer").InnerText;

                XmlNode track = tracks.SelectSingleNode("key[text()='"+id+"']/following-sibling::dict");
                string album = track.SelectSingleNode("key[text()='Album']/following-sibling::string").InnerText; //XElement.Parse(track.Descendants("key").Single(k => k.Value == "Album").NextNode.ToString());
                string location = track.SelectSingleNode("key[text()='Location']/following-sibling::string").InnerText; 

                result[i] = new Track();
                result[i].Filename = Uri.UnescapeDataString(location.Substring(location.LastIndexOf("/") + 1));
                result[i].Album = album;
                result[i].FullPath = Uri.UnescapeDataString(location).Substring(locationOffset).Replace("/", "\\"); 
                result[i].RelativePath = DirectoryFilter.Filt(result[i].Album) + "\\" + result[i].Filename;
                i++;
            }
            return result;
        }

    }
}
